<?php
namespace app\api\controller;
use app\model\OpAccount;
use app\model\Token;
use app\model\Recharge;
use app\model\ItemConsume;
class Zhihu {
    // 获取已授权的再跑的账户
    public function acc(){
        $wh[] = ['acc.acc_type','=',3];
        $wh[] = ['acc.is_banned','=',1];
        $wh[] = ['acc.status','=',1];
        $wh[] = ['acc.is_accredit','=',1];
        $wh[] = ['acc.jindu','=',5];
        $wh[] = ['i.status','=',1];
        $wh[] = ['i.is_finish','=',0];
        $ids = OpAccount::alias('acc')
        ->join('items i','i.op_account_id = acc.id','LEFT')
        ->where($wh)->column('acc.id');
        
        if(!empty($ids)){
            return $ids;
        }else{
            return false;
        }
    }
    //获取所有的Token和账户id
    function get_acc_id_token($ids){
        $wh[] = ['acc_id','in',$ids];
        $wh[] = ['group','=','zhihu'];
        $list = Token::field('access_token,acc_id,advertiser_ids')->where($wh)->select()->toArray();
        if(!empty($list)){
            return $list;
        }else{
            return false;
        }
    }
    //获取账户流水
    public function flows($token,$uid){
        $t = date("Y-m-d", strtotime("-1 day"));
        $qm = $this->signature($uid,$token);
        $headers = [
            'Content-Type:application/json',
        ];
        $url = 'https://xg.zhihu.com/api/v1/stat/api/getStatData?timestamp='.time().'&signature='.$qm.'&dataType=USER&groupUnit=BY_DAY&startDate='.$t.'&endDate='.$t.'&advertiserIds='.$uid.'&userId='.$uid;
        try {
            $rs = json_decode(http_get($url,$headers),true);
            if($rs['code'] == 100){
                $arr = ['code'=>1,'msg'=>'','data'=>$rs['data'][0]['basicStatData']];
                return $arr;
            }else{
                return $rs;
            }
        } catch (\Throwable $th) {
            //throw $th;
            $arr = ['code'=>0,'msg'=>$th->getMessage()];
            return $arr;
        }
    }
    
    //签名
    function signature($uid,$token){
        $str = $uid.$token.time();
        $str = md5($str);
        return $str;
    }
    // 获取消耗
    public function consume(){
        set_time_limit(0);
        $ids = $this->acc();
        if($ids != false){
            $list = $this->get_acc_id_token($ids);
            if($list != false){
                foreach($list as $k=>$v){
                    $r = $this->flows($v['access_token'],$v['advertiser_ids']);
                    if($r['code'] == 1){
                        $r['data']['advertiser_id'] = $v['advertiser_ids'];
                        $r['data']['cost'] = round($r['data']['cost']/100,2);
                        $this->add_acc_consume($r['data']);
                    }else{
                        echo '获取知乎已授权账户的ID:'.$v['advertiser_ids'].'的消耗失败，原因：'.$r['msg'];
                    }
                    
                }
            }else{
                echo '获取知乎已授权账户的token失败';
            }
        }else{
            echo '获取知乎已授权账户失败';
        }
    }
    // 添加消耗
    function add_acc_consume($data){
        $w[] = ['acc.name_id','=',$data['advertiser_id']];
        $rs = OpAccount::alias('acc')
        ->field('acc.id,acc.operate_id,i.id items_id,i.operate_type')
        ->join('items i','acc.id = i.op_account_id')
        ->where($w)->find();

        $r = Recharge::where('op_account_id',$rs['id'])->order('create_time desc')->find();

        $d['time'] = strtotime($data['date']);
        $d['currency'] = $data['cost'];
        // $d['balance'] = $data['balance'];
        $d['items_id'] = $rs['items_id'];
        $d['operation_id'] = $rs['operate_id'];
        $d['op_account_id'] = $rs['id'];
        $d['is_operate'] = $rs['operate_type'];
        $d['rebate'] = $r['rebate'];
        $d['channel_rebate'] = $r['channel_rebate'];
        $d['consume_profit'] = 0;
        // $d['acc'] =$data['advertiser_id'];
        
        try {
            $w1[] = ['items_id','=',$d['items_id']];
            $w1[] = ['time','=',$d['time']];
            $r1 = ItemConsume::where($w1)->value('id');
            
            if(empty($r1)){
                ItemConsume::create($d);
                echo $data['advertiser_id'].'消耗添加成功';
            }else{
                ItemConsume::where($w1)->update($d);
                echo $data['advertiser_id'].'消耗更新成功';
            }
            
        } catch (\Throwable $th) {
            //throw $th;
            echo $data['advertiser_id'].'消耗添加失败。原因：'. $th->getMessage();
        }
        
        
    }

    // 测试
    function ff(){
        $this->flows('10f2eb111c3048019cf3c25b72b72d5d',31035);
        dump('sds');
    }
























}